import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import context from './context'
import './App.css'
// 解构context中的Provider
const { Provider } = context
export default class App extends Component {
  state = {
    todoList: [
      {
        id: 1,
        todoName: '吃饭',
        isDone: false,
      },
      {
        id: 2,
        todoName: '睡觉',
        isDone: true,
      },
    ],
  }

  //组件挂载的时候订阅
  componentDidMount() {
    // 只要是生命周期钩子函数里的this,一定指向组件实例
    // 添加任务
    this.addToken = PubSub.subscribe('add', (topic, todoName) => {
      // 根据任务名,创建任务对象
      // 永远获取数组中最后一条数据的id然后加1.作为新数据的id .
      // 要注意,如果数组中没有任何数据,第一条数据的id就是1
      const { todoList } = this.state
      const id = todoList.length ? todoList[todoList.length - 1].id + 1 : 1
      const todo = {
        id,
        todoName,
        isDone: false,
      }

      const newTodoList = [...todoList]
      newTodoList.push(todo)
      this.setState({
        todoList: newTodoList,
      })
    })

    // 修改任务状态
    this.updateToken = PubSub.subscribe('update', (topic, id) => {
      const newTodoList = this.state.todoList.map((item) => {
        if (item.id === id) {
          item.isDone = !item.isDone
        }
        return item
      })
      this.setState({
        todoList: newTodoList,
      })
    })
  }
  // 组件卸载的时候,清除指定订阅
  componentWillUnmount() {
    PubSub.unsubscribe(this.addToken)
    PubSub.unsubscribe(this.updateToken)
  }
  render() {
    return (
      <Provider value={this.state.todoList}>
        <div className="todo-container">
          <div className="todo-wrap">
            <Header></Header>
            <div>
              <List></List>
              <Footer></Footer>
            </div>
          </div>
        </div>
      </Provider>
    )
  }
}
